<template>
  <div>
    <div class="search_box">
      <el-form :inline="true" ref="ruleFormRef" :model="formData">
        <el-form-item>
          <el-input
            v-model="formData.name"
            placeholder="推广链接名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-input v-model="formData.linkId" placeholder="LinkID" clearable />
        </el-form-item>
        <el-form-item v-auth="'api:agent:promotion:search'">
          <el-button type="primary" @click="getList(1)">查询</el-button>
          <el-button type="primary" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- table列表 -->
    <div class="tableBox">
      <div class="batch_box">
        <!-- 新增 -->
        <el-button
          type="primary"
          @click="add"
          v-auth="'api:agent:promotion:add'"
        >
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button type="primary" @click="importLink">
          <el-icon>
            <Download />
          </el-icon>
          导入链接
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        :expand-row-keys="expands"
        :height="tableHeight"
        @expand-change="expandChange"
        ref="tableRef"
      >
        <el-table-column type="expand" width="80">
          <template #default="scope">
            <div m="4" class="openBox">
              <div class="open">
                <p>
                  <strong>投放链接</strong>
                  <span
                    class="hover"
                    style="margin-left: 10px"
                    @click.stop="copyLink(tfLink + scope.row?.linkId)"
                  >
                    点击复制
                  </span>
                </p>
                <p>
                  {{ tfLink + scope.row?.linkId }}
                </p>
              </div>
              <div class="open">
                <p class="p">
                  <span>
                    <strong>小程序路径</strong>
                    <span
                      class="hover"
                      style="margin-left: 10px"
                      @click.stop="copy(scope.row, '')"
                      v-if="user.userAppObj?.appType == 'wx'"
                    >
                      点击复制
                    </span>
                  </span>

                  <span v-if="tt_album_id" class="tt_album">
                    <span>抖音剧目id：{{ tt_album_id }}</span>
                    <span>抖音剧集id：{{ tt_episode_id }}</span>
                    <span>小程序id：{{ user.userAppObj?.appId || "" }}</span>
                  </span>
                </p>
                <template v-if="user.userAppObj?.appType == 'wx'">
                  {{ linkUrl }}
                </template>
                <template v-if="user.userAppObj?.appType == 'dy'">
                  <p v-if="pageLink">
                    启动页面：{{ pageLink }}
                    <span
                      class="hover"
                      style="margin-left: 15px"
                      @click.stop="copy(scope.row, 1)"
                    >
                      点击复制
                    </span>
                  </p>
                  <p>
                    启动参数：
                    {{ pageUrl }}
                    <span
                      class="hover"
                      style="margin-left: 15px"
                      @click.stop="copy(scope.row, 2)"
                    >
                      点击复制
                    </span>
                  </p>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="linkId" prop="linkId" min-width="180">
          <template #default="scope">
            <p>
              <span>{{ scope.row.linkId }}</span>
            </p>
            <p>
              <span class="hover" @click="expandChange(scope.row)">
                {{ "查看推广链接" }}</span
              >
            </p>
          </template>
        </el-table-column>
        <el-table-column label="推广链接名称" prop="linkName" min-width="120" />
        <el-table-column label="小程序名称" prop="appName" min-width="120" />
        <el-table-column label="推广目标" prop="wxPromotion" min-width="120">
          <template #default="scope">
            <p>
              ID：<span>{{ scope.row.operaId }}</span>
            </p>
            <p>
              剧名：<span>{{ scope.row.operaName }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column
          label="关注信息"
          prop="followPlatType"
          min-width="120"
        />
        <el-table-column label="配置信息" prop="name" min-width="165">
          <template #default="scope">
            <p>
              每集价格：<span class="green">
                {{ scope.row.unblockCoinAmount }}
              </span>
            </p>
            <p>
              付费卡点：<span class="green">
                {{ scope.row.chargeEpisodeNo }}
              </span>
            </p>
            <p>
              充值模板：<span class="green">
                {{ scope.row.isDiffRecharge ? "区分首充" : "不区分首充" }}
              </span>
            </p>
            <p>
              推广平台：<span>{{ platformActive(scope.row.platform) }}</span>
            </p>
            <p>
              推链维度：<span>{{ scope.row.feedbackDescribe }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="100">
          <template #default="props">
            <span
              class="operationClick isBlock"
              type="primary"
              @click="handleClick(props.row, '编辑')"
              v-auth="'api:agent:promotion:update'"
            >
              信息编辑
            </span>
            <span
              class="operationClick isBlock"
              type="primary"
              @click="handleClick(props.row, '收费')"
              v-auth="'api:agent:promotion:update'"
            >
              收费设置
            </span>
            <span
              class="operationClick isBlock"
              type="primary"
              @click="handleClick(props.row, '回传')"
              v-auth="'api:agent:promotion:backset'"
            >
              回传设置
            </span>
            <span
              class="operationClick isBlock"
              type="primary"
              @click="handleClick(props.row, '删除')"
              v-auth="'api:agent:promotion:delete'"
            >
              删除
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <customPagination
        class="pageBox"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
      />
    </div>

    <!-- 添加/编辑链接 -->
    <addLink ref="addLinkRef" @success="getList(1)" />

    <!-- 回传设置 -->
    <returnSet ref="returnSettingRef" @success="getList(1)" />

    <!-- 收费设置 -->
    <paySetting ref="paySettingRef" @success="getList(1)" />

    <!-- 导入 -->
    <importDialog ref="importRef" @success="getList(1)" />
  </div>
</template>

<script setup lang="ts">
import { Plus, Download } from "@element-plus/icons-vue";
import addLink from "./components/addLinkDialog.vue";
import returnSet from "./components/returnSet.vue";
import paySetting from "./components/paySet.vue";
import importDialog from "./components/importDialog.vue";
import customPagination from "@/components/CustomPagination/index.vue";
import { copyLink } from "@/utils/tools";
import { metadata } from "@/api/episodeList/index";
import {
  promotionSearchList,
  promotionsDelete,
} from "@/api/promotionLink/index";
import { useUserStore } from "@/store/modules/user";
import { useRouter } from "vue-router";

const userStore = useUserStore();

const user = useUserStore().user;
const router = useRouter();
const loading = ref<boolean>(false);
const pageLink = "pages/login/index";
const pageUrl = ref("");
const form = {
  pageNo: 1,
  pageSize: 10,
  name: "",
  linkId: "", // 链接名称
};

const pageObj = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const tableData = ref([]);
const formData = ref(Object.assign({}, form));
const tableHeight = ref();
const tableRef = ref();
const expands = ref(<any>[]); // 展开行list
const linkUrl = ref(""); // 复制链接
const tfLink = ref(
  `${window.location.origin}/api/tracking/ad_fallback?link_id=`
);

const tt_album_id = ref("");
const tt_episode_id = ref("");

const importRef = ref();
const importLink = () => {
  importRef.value.showDialog();
};

const addLinkRef = ref();
const add = () => {
  addLinkRef.value.showDialog();
};

// 推广平台
const platformActive = (val: string) => {
  let str;
  if (val === "xt") {
    str = "星图";
  } else if (val === "tt2") {
    str = "巨量2.0";
  }
  return str;
};

// 查询列表
const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = pageObj.pageNo;
  formData.value.pageSize = pageObj.pageSize;

  loading.value = true;
  promotionSearchList(formData.value)
    .then((res: Record<string, any>) => {
      nextTick(() => {
        if (!res?.data) return;
        tableData.value = res?.data;
        pageObj.total = Number(res?.total);
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置
const resetForm = () => {
  formData.value = Object.assign(formData.value, form);
  getList(1);
};

// 操作
const ruleFormRef = ref();
const returnSettingRef = ref();
const paySettingRef = ref();
const handleClick = (val: Record<string, any>, text: string) => {
  if (text == "编辑") {
    addLinkRef.value.showDialog(val);
  } else if (text == "回传") {
    returnSettingRef.value.showDialog(val);
  } else if (text == "收费") {
    paySettingRef.value.showDialog(val);
  } else if (text == "删除") {
    ElMessageBox.confirm("确认删除这条数据吗?", "提醒", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        promotionsDelete(val.id).then(() => {
          ElMessage.success("删除成功");
          getList(1);
        });
      })
      .catch(() => {});
  }
};

// 查看链接 / 打开/关闭展开行
const expandChange = (row: any) => {
  console.log("row---", row);
  console.log("user----", user);
  if (!row.id) return;
  if (expands.value.includes(row.id)) {
    // 关闭
    expands.value = expands.value.filter(
      (val: Record<string, any>) => val !== row.id
    );
    tt_album_id.value = "";
    tt_episode_id.value = "";
  } else {
    // 如果用户通过缓存没获取到小程序对象信息,则重新登录
    if (!user?.userAppObj?.appType) {
      // console.log("router---", router);
      userStore.clearToken();
      localStorage.removeItem("userAppid");
      localStorage.removeItem("userApps");
      localStorage.removeItem("firstData");
      localStorage.removeItem("appObj");
      window.location.href = `/login`;
      return;
    }
    let link = `pages/login/index?url=/pages/hot/play&linkId=${row?.linkId}&id=${row?.operaId}&episode=${row?.episode}`;
    // 每次打开重置
    tt_album_id.value = "";
    tt_episode_id.value = "";
    // 为星图推广时，调用接口获取 抖音剧目id
    if (user.userAppObj?.appType == "wx") {
      linkUrl.value = `${link}`;
    } else if (user.userAppObj?.appType == "dy") {
      metadata(row.operaId).then((res: Record<string, any>) => {
        tt_album_id.value = res?.album_id;
        tt_episode_id.value = res?.episodes[row?.episode - 1].episode_id;
        linkUrl.value = "";
        pageUrl.value = `url=/pages/hot/play&linkId=${row?.linkId}&id=${row?.operaId}&episode=${row?.episode}&tt_album_id=${tt_album_id.value}&tt_episode_id=${tt_episode_id.value}&advertiserId=__ADVERTISER_ID__`;
      });
    }

    // 打开
    expands.value = []; //添加该代码实现手风琴模式，删除该代码取消手风琴模式
    expands.value.push(row.id);
  }
  // console.log("expands.value---", expands.value);
};

// 复制
const copy = (val: Record<string, any>, type: any) => {
  // console.log("val---", val);
  let link = `pages/login/index?url=/pages/hot/play&linkId=${val?.linkId}&id=${val?.operaId}&episode=${val?.episode}`;
  if (user.userAppObj?.appType == "wx") {
    copyLink(link);
    return;
  } else if (user.userAppObj?.appType == "dy") {
    let temp = link.split("?");
    if (type === 1) {
      link = temp[0];
    } else if (type === 2) {
      link =
        temp[1] +
        `&tt_album_id=${tt_album_id.value}&tt_episode_id=${tt_episode_id.value}&advertiserId=__ADVERTISER_ID__`;
    }
    copyLink(link);
  }
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

onMounted(() => {
  getList();
  // 设置表格初始高度为innerHeight-offsetTop-表格底部与浏览器底部距离：66 + 顶部固定高度：50
  tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 118;
  // 监听浏览器高度变化
  window.onresize = () => {
    tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 118;
  };
});
</script>

<style lang="scss" scoped>
.tableBox {
  padding: 10px;
  margin-top: 10px;
  background-color: #fff;
  border-radius: 4px;

  :deep(th.el-table__cell) {
    background-color: #f5f5f5;
  }

  .batch_box {
    margin-bottom: 10px;
  }
}

.openBox {
  padding: 18px 50px;

  .open {
    margin-bottom: 20px;

    .p {
      margin: 6px 0;

      .tt_album {
        margin-left: 50px;
        font-weight: bold;

        span {
          margin-left: 50px;
        }
      }
    }
  }

  .linkBox {
    width: 100%;
    padding: 14px;
    font-size: 14px;
    line-height: 24px;
    cursor: pointer;
    background: #f0f9eb;
    border: 1px solid #c2e7b0;
    border-radius: 4px;
  }
}
</style>
